package com.mapler.gbot;

import com.mapler.service.INotifier;
import com.mapler.utility.Util;
import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Mithun
 */
public class BotRunner extends javax.swing.JDialog implements INotifier {

    public ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
    private static Logger log = Logger.getLogger(BotRunner.class);
    private INotifier iNotifier;

    /**
     * Creates new form BotRunner
     */
    public BotRunner(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        PropertyConfigurator.configure("./src/log4j.properties");
        initComponents();
        this.getiNotifier();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTFProxy = new javax.swing.JTextField();
        vpnusername = new javax.swing.JTextField();
        vpnpassword = new javax.swing.JTextField();
        jTFipchangeTime = new javax.swing.JTextField();
        start = new javax.swing.JButton();
        jBStop = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        message = new javax.swing.JLabel();
        Exit = new javax.swing.JButton();
        jTFNGFXLink = new javax.swing.JTextField();
        jTFCLRobotLink = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jCBClearLog = new javax.swing.JCheckBox();
        jCBClearBrowser = new javax.swing.JCheckBox();
        jCBClearTmp = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        start.setText("Connect");
        start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startActionPerformed(evt);
            }
        });

        jBStop.setText("Disconnect");
        jBStop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBStopActionPerformed(evt);
            }
        });

        jLabel1.setText("IP change time in min");

        jLabel6.setText("Password");

        jLabel5.setText("Username");

        jLabel2.setText("Proxy");

        Exit.setText("Stop & Exit");
        Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitActionPerformed(evt);
            }
        });

        jTFNGFXLink.setText("http://nigeria-forex.com/");

        jTFCLRobotLink.setText("http://www.clirobot.com/");

        jLabel3.setText("CL Robot link");

        jLabel4.setText("NGFX link");

        jCBClearLog.setText("Clear log file on IP change");

        jCBClearBrowser.setText("Close browser on IP change");

        jCBClearTmp.setText("Cler tmp file on IP change");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(message, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(105, 105, 105)
                .addComponent(start)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jBStop)
                .addGap(18, 18, 18)
                .addComponent(Exit)
                .addGap(77, 77, 77))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCBClearTmp)
                    .addComponent(jCBClearBrowser)
                    .addComponent(jCBClearLog)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jTFipchangeTime)
                        .addComponent(vpnpassword)
                        .addComponent(vpnusername)
                        .addComponent(jTFProxy, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTFCLRobotLink, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
                        .addComponent(jTFNGFXLink)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(message, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFCLRobotLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFNGFXLink, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFProxy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vpnusername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vpnpassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTFipchangeTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCBClearLog)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCBClearBrowser)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCBClearTmp)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Exit)
                    .addComponent(start)
                    .addComponent(jBStop))
                .addGap(26, 26, 26))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void startActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startActionPerformed
        if (jTFProxy.getText().isEmpty() || vpnusername.getText().isEmpty() || vpnpassword.getText().isEmpty()) {
            iNotifier.notify("Connect:: Proxy, user name and password can not be empty ");
            return;
        }
        if (jTFipchangeTime.getText() == null || jTFipchangeTime.getText().isEmpty()) {
            iNotifier.notify("Connect:: IP Chanange time cant not be empty ");
            return;
        }
        final int ipChangeTime = Integer.parseInt(jTFipchangeTime.getText());

        final Runnable runConnect = new Runnable() {
            @Override
            public void run() {
                try {
                    doRun();
                    iNotifier.notify("Connect::Going to check URI activated.");
                    boolean isConnected = checkURI();
                    while (!isConnected) {
                        iNotifier.notify("Connect::URI is not activated.Going change VPN connection ");
                        doRun();
                        isConnected = checkURI();
                    }
                    iNotifier.notify("Connect::Waiting for next execution ... ");
                } catch (Throwable ex) {
                    log.error("Error on vpn connection :" + ex);
                }
            }
        };
        executor.scheduleAtFixedRate(runConnect, 1, ipChangeTime * 60, TimeUnit.SECONDS);

    }//GEN-LAST:event_startActionPerformed

    private void doRun() {
        try {
            iNotifier.notify("Connect::Going to disconnected VPN.");
            boolean disconnect = Util.disConnect(jTFProxy.getText(), vpnusername.getText(), vpnpassword.getText());
            if (!disconnect) {
                iNotifier.notify("Connect:: unable to disconnec VPN ");
                log.debug("Connect:goVPN:: unable to disconnect VPN(no more further action) for " + jTFProxy.getText());
            } else {
                iNotifier.notify("Signup:: disconnected from VPN ");
                log.debug("Signup:: disconnected form VPN ");
            }
            Util.wait(2);
            iNotifier.notify("Connect::Going to connected VPN.");
            boolean connect = Util.connect(jTFProxy.getText(), vpnusername.getText(), vpnpassword.getText());
            if (!connect) {
                iNotifier.notify("Connect::Connected VPN.");
                log.debug("Connect:: Connected for " + jTFProxy.getText());
            } else {
                iNotifier.notify("Connect:: Connected VPN.");
                log.debug("Connect::Connected for " + jTFProxy.getText());
            }
            if (jCBClearLog.isSelected()) {
                iNotifier.notify("Connect:: Going to clear log file.");
                clearLogFile();
            }

            if (jCBClearBrowser.isSelected()) {
                iNotifier.notify("Connect:: Going to close browser.");
                closeBrowser();
            }

            if (jCBClearTmp.isSelected()) {
                iNotifier.notify("Connect:: Going to delete temp file.");
                Util.deleteFXTmpDirectory();
            }
        } catch (Throwable ex) {
            log.error("Error on vpn connection :" + ex);
        }
    }

    private void clearLogFile() {
        try {
            File file = new File("C:\\ilog\\irobot.log");
            if (file.exists()) {
                PrintWriter writer = new PrintWriter(file);
                writer.print("");
                writer.close();
            }
        } catch (Throwable ex) {
            log.debug("Error :::" + ex);
        }
    }

    private void closeBrowser() {
        try {
            Runtime.getRuntime().exec("taskkill /F /IM firefox.exe");

        } catch (Throwable ex) {
            log.error("CloseBrowser::Error on closing :" + ex);
        }
    }

    private boolean checkURI() {
        boolean isConnected = this.validateURI();
        if (isConnected) {
            return true;
        }
        isConnected = this.validateURI();
        if (isConnected) {
            return true;
        }
        isConnected = this.validateURI();
        if (isConnected) {
            return true;
        }

        return false;
    }

    private boolean validateURI() {
        try {
            if (jTFCLRobotLink.getText().isEmpty()) {
                URLConnection connection = new URL(jTFCLRobotLink.getText()).openConnection();
                connection.connect();
            }

            if (!jTFNGFXLink.getText().isEmpty()) {
                URLConnection connection = new URL(jTFNGFXLink.getText()).openConnection();
                connection.connect();
            }
            return true;
        } catch (Throwable ex) {
            ex.printStackTrace();
            log.debug("Error:::" + ex);
        }
        return false;
    }

    private void jBStopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBStopActionPerformed
        try {
            boolean disconnect = Util.disConnect(jTFProxy.getText(), vpnusername.getText(), vpnpassword.getText());
            if (!disconnect) {
                iNotifier.notify("disconnec:: unable to disconnec VPN ");
                log.debug("disconnec:: unable to disconnect VPN(no more further action) for " + jTFProxy.getText());
            } else {
                iNotifier.notify("disconnec:: disconnected from VPN ");
                log.debug("disconnec:: disconnected form VPN ");
            }
            executor.shutdown();
            Util.wait(1);
            executor = Executors.newScheduledThreadPool(10);
        } catch (Throwable ex) {
            log.error("disconnec::Error on vpn connection :" + ex);
        }
    }//GEN-LAST:event_jBStopActionPerformed

    private void ExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitActionPerformed
        try {
            boolean disconnect = Util.disConnect(jTFProxy.getText(), vpnusername.getText(), vpnpassword.getText());
            if (!disconnect) {
                iNotifier.notify("disconnec:: unable to disconnec VPN ");
                log.debug("disconnec:: unable to disconnect VPN(no more further action) for " + jTFProxy.getText());
            } else {
                iNotifier.notify("disconnec:: disconnected from VPN ");
                log.debug("disconnec:: disconnected form VPN ");
            }
            executor.shutdown();
            Runtime.getRuntime().exec("taskkill /F /IM java.exe");

        } catch (Throwable ex) {
            log.error("disconnec::Error on vpn connection :" + ex);
        }
    }//GEN-LAST:event_ExitActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BotRunner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BotRunner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BotRunner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BotRunner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BotRunner dialog = new BotRunner(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Exit;
    private javax.swing.JButton jBStop;
    private javax.swing.JCheckBox jCBClearBrowser;
    private javax.swing.JCheckBox jCBClearLog;
    private javax.swing.JCheckBox jCBClearTmp;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField jTFCLRobotLink;
    private javax.swing.JTextField jTFNGFXLink;
    private javax.swing.JTextField jTFProxy;
    private javax.swing.JTextField jTFipchangeTime;
    private javax.swing.JLabel message;
    private javax.swing.JButton start;
    private javax.swing.JTextField vpnpassword;
    private javax.swing.JTextField vpnusername;
    // End of variables declaration//GEN-END:variables

    @Override
    public void notify(final String info) {
        try {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    message.setText(info);
                }
            });
        } catch (Throwable ex) {
            log.debug("notify:: Error causes " + ex.getMessage());
        }
    }

    @Override
    public void write(String info) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public INotifier getiNotifier() {
        if (iNotifier == null) {
            iNotifier = this;
        }
        return iNotifier;
    }

    public void setiNotifier(INotifier iNotifier) {
        this.iNotifier = iNotifier;
    }
}
